<template>
  <div class="article-preview">
    <div class="header">
      <a-page-header
        :title="article.title"
        @back="handleBack"
      />
    </div>
    
    <div class="article-meta">
      <span>
        <calendar-outlined /> {{ formatDate(article.createTime) }}
      </span>
      <span v-if="article.categoryId">
        <folder-outlined /> {{ getCategoryName(article.categoryId) }}
      </span>
      <span>
        <eye-outlined /> {{ article.viewCount || 0 }} 次阅读
      </span>
      <span>
        <tag-outlined /> {{ article.status === 1 ? '已发布' : '草稿' }}
      </span>
    </div>
    
    <div class="article-cover" v-if="article.coverImage">
      <img :src="'http://192.168.1.10:8080'+article.coverImage" alt="封面图片">
    </div>
    
    <div class="article-content" ref="contentRef"></div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { CalendarOutlined, FolderOutlined, EyeOutlined, TagOutlined } from '@ant-design/icons-vue';
import { getArticleDetail } from '@/api/article';
import { useCategoryStore } from '@/stores/category';
import hljs from 'highlight.js';
import 'highlight.js/styles/atom-one-dark.css';

const route = useRoute();
const router = useRouter();
const categoryStore = useCategoryStore();
const article = ref({});
const contentRef = ref(null);

onMounted(async () => {
  // 加载分类
  await categoryStore.getCategoryList();
  
  if (route.params.id) {
    const id = parseInt(route.params.id.toString());
    try {
      const res = await getArticleDetail(id);
      article.value = res;
      
      // 等待DOM更新后处理代码块
      await nextTick();
      if (contentRef.value) {
        contentRef.value.innerHTML = article.value.content;
        processCodeBlocks();
      }
    } catch (error) {
      console.error('获取文章详情失败:', error);
    }
  }
});

// 处理代码块，添加苹果风格控制栏
const processCodeBlocks = () => {
  if (!contentRef.value) return;
  
  // 初始化代码高亮
  hljs.configure({
    languages: ['javascript', 'typescript', 'python', 'java', 'html', 'css', 'bash', 'json', 'sql']
  });
  
  // 查找所有代码块容器
  const codeBlockContainers = contentRef.value.querySelectorAll('.ql-code-block-container');
  codeBlockContainers.forEach((container) => {
    // 移除选择器和不必要的元素
    const selectElement = container.querySelector('.ql-ui');
    if (selectElement) {
      selectElement.style.display = 'none';
    }
    
    // 如果已经处理过，跳过
    if (container.previousElementSibling?.className === 'code-control-bar') return;
    
    // 添加苹果风格类
    container.classList.add('apple-style-code');
    
    // 获取语言
    let language = 'code';
    const codeBlocks = container.querySelectorAll('.ql-code-block');
    if (codeBlocks.length > 0) {
      const dataLanguage = codeBlocks[0].getAttribute('data-language');
      if (dataLanguage) {
        language = dataLanguage;
      }
    }
    
    // 创建控制栏
    const controlBar = document.createElement('div');
    controlBar.className = 'code-control-bar';
    
    // 语言标签
    const langLabel = document.createElement('span');
    langLabel.className = 'code-lang-label';
    langLabel.textContent = language.toUpperCase();
    controlBar.appendChild(langLabel);
    
    // 复制按钮
    const copyBtn = document.createElement('button');
    copyBtn.className = 'code-copy-btn';
    copyBtn.textContent = '复制代码';
    copyBtn.onclick = function(e) {
      e.preventDefault();
      e.stopPropagation();
      const codeContent = Array.from(codeBlocks)
        .map(block => block.textContent || '')
        .join('\n');
      navigator.clipboard.writeText(codeContent)
        .then(() => {
          copyBtn.textContent = '已复制!';
          setTimeout(() => {
            copyBtn.textContent = '复制代码';
          }, 2000);
        })
        .catch(err => {
          console.error('复制失败:', err);
        });
    };
    controlBar.appendChild(copyBtn);
    
    // 将控制栏插入到代码块前
    container.parentNode?.insertBefore(controlBar, container);
    
    // 应用代码高亮到每个代码行
    codeBlocks.forEach(block => {
      try {
        // 确保代码块没有额外的内部标签
        if (block.childNodes.length > 1) {
          block.innerHTML = block.textContent || '';
        }
        hljs.highlightElement(block);
      } catch (e) {
        console.error('代码高亮错误:', e);
      }
    });
  });
};

const handleBack = () => {
  router.go(-1);
};

const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleString();
};

const getCategoryName = (categoryId) => {
  const category = categoryStore.categoryList.find(c => c.id === categoryId);
  return category ? category.name : '未分类';
};
</script>

<style>
.article-preview {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.header {
  margin-bottom: 20px;
}

.article-meta {
  color: #8c8c8c;
  margin: 16px 0;
  display: flex;
  gap: 20px;
}

.article-cover {
  margin-bottom: 20px;
}

.article-cover img {
  width: 100%;
  max-height: 400px;
  object-fit: cover;
  border-radius: 8px;
}

.article-content {
  line-height: 1.8;
}

/* 苹果风格代码块样式优化 */
.ql-code-block-container.apple-style-code {
  position: relative;
  background-color: #282c34;
  color: #abb2bf;
  border-radius: 0 0 6px 6px;
  padding: 20px;
  margin: 0 0 20px 0;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 14px;
  line-height: 1.6;
  overflow: auto;
  border: 1px solid #1c1e25;
  border-top: none;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}

/* 隐藏Quill编辑器UI元素 */
.ql-code-block-container .ql-ui {
  display: none !important;
}

/* 代码行样式 */
.ql-code-block {
  white-space: pre;
  padding: 0;
  margin: 0 0 2px 0;
  font-family: inherit;
  line-height: 1.6;
  tab-size: 4;
  -moz-tab-size: 4;
}

/* 控制栏样式优化 */
.code-control-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(to bottom, #3a3f4b, #2f333d);
  border: 1px solid #1c1e25;
  border-bottom: none;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  height: 36px;
  padding: 0 12px;
  color: #d7dae0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
  font-size: 12px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.2);
}

.code-lang-label {
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  font-size: 11px;
  padding: 2px 6px;
  background-color: rgba(255,255,255,0.1);
  border-radius: 3px;
}

.code-copy-btn {
  background-color: rgba(255,255,255,0.1);
  border: none;
  border-radius: 4px;
  color: #d7dae0;
  padding: 4px 10px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
  font-weight: 500;
}

.code-copy-btn:hover {
  background-color: rgba(255,255,255,0.2);
  color: white;
}

.code-copy-btn:active {
  transform: translateY(1px);
}

/* 滚动条样式 */
.ql-code-block-container::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.ql-code-block-container::-webkit-scrollbar-track {
  background: #21252b;
  border-radius: 4px;
}

.ql-code-block-container::-webkit-scrollbar-thumb {
  background: #4e5562;
  border-radius: 4px;
}

.ql-code-block-container::-webkit-scrollbar-thumb:hover {
  background: #5a6173;
}

/* 代码行间距 */
.ql-code-block + .ql-code-block {
  margin-top: 0;
}
</style> 